const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    active: 1,
    course: {},
    courselist: [], 
    teacherintroduce: {},
    courseintroduce: {},
    courseEvaluate: {},
    courseEvaluate1: [], 
    titleList: ["课程详情", "课程列表", "名师介绍", "课程评价"],
    courseDetailData: {},
    current: 0,
    courseid: 0,
    isPurchased: false, 
    currentVideo: null,
    cid:0,
    evaluationCount: 0, // 评价次数
    collectionCount: 0,  // 收藏次数
    isCollected: false, // 课程是否已收藏
    loginUserInfo: null // 用户登录信息
  },

  chooseItem(e) {
    this.setData({
      current: e.target.dataset.index
    })
  },

  onChange(event) {
    wx.showToast({
      title: `切换到标签 ${event.detail.name}`,
      icon: 'none',
    });
  },

  swiperChanged(e) {
    this.setData({
      current: e.detail.current
    })
  },

  onCourseItemClick(e) {
    const { loginUserInfo } = this.data;
    const { item } = e.currentTarget.dataset;
    
    if (!loginUserInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    if (!this.data.isPurchased) {
      wx.showToast({
        title: '请先购买课程',
        icon: 'none'
      });
      return;
    }
    
    // 已购买状态下才能播放视频并更新学习次数
    this.setData({
      currentVideo: item
    });
    
    // 更新学习次数
    this.updateStudyNumber();
  },

  toEvaluate() {
    const { cid } = this.data;
    wx.navigateTo({
      url: `/course/pages/toEvaluation/toEvaluation?cid=${cid}`,
    });
  },

  toEvaluateList() {
    const { cid } = this.data;
    wx.navigateTo({
      url: `/course/pages/evaluationList/evaluationList?cid=${cid}`,
    });
  },

  buyCourse() {
    const { loginUserInfo } = this.data;
    const { cid } = this.data;
    
    if (!loginUserInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    const userId = loginUserInfo.id;
    
    wx.showModal({
      title: '确认购买',
      content: `您确定要购买《${this.data.course.courseName}》课程吗？`,
      success: (res) => {
        if (res.confirm) {
          wx.request({
            url: `http://localhost:8080/courseOrder`,
            method: "POST",
            data: {
              userId,
              courseId: cid,
              orderStatus: 1, 
              realPay: this.data.course.discountPrice
            },
            success: (resp) => {
              if (resp.data.code === 200) {
                wx.showToast({
                  title: '购买成功',
                  icon: 'success'
                });
                
                // 更新购买状态
                this.setData({
                  isPurchased: true
                });
              } else {
                wx.showToast({
                  title: '购买失败',
                  icon: 'none'
                });
              }
            },
            fail: (err) => {
              console.error("购买课程失败", err);
              wx.showToast({
                title: '购买失败',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  updateStudyNumber() {
    const { courseid } = this.data;
    
    wx.request({
      url: `http://localhost:8080/course/${courseid}/updateStudyNumber`,
      method: "PUT",
      success: (resp) => {
        if (resp.data.code === 200) {
          // 成功更新学习次数后，刷新课程信息
          this.refreshCourseInfo();
        } else {
          console.error("学习次数更新失败");
        }
      },
      fail: (err) => {
        console.error("学习次数更新失败", err);
      }
    });
  },

  refreshCourseInfo() {
    wx.request({
      url: `http://localhost:8080/course/${this.data.courseid}`,
      method: "GET",
      success: (courseResp) => {
        if (courseResp.data.code === 200) {
          this.setData({
            course: courseResp.data.data
          });
        }
      }
    });
  },

  fetchAndFilterCourseVideos() {
    const { courseid } = this.data;

    wx.request({
      url: `http://localhost:8080/courseVideo`,
      method: "GET",
      success: (resp) => {
        const filteredVideos = resp.data.data.filter(item => {
          return item.courseId === courseid || item.id === courseid;
        });

        this.setData({
          courselist: filteredVideos
        });
      },
      fail: (err) => {
        console.error("获取视频列表失败", err);
      }
    });
  },

  fetchEvaluationCount() {
    const { cid } = this.data;
    
    wx.request({
      url: `http://localhost:8080/courseEvaluate/count`,
      method: "GET",
      data: {
        courseId: cid
      },
      success: (resp) => {
        if (resp.data.code === 200) {
          this.setData({
            evaluationCount: resp.data.data || 0
          });
        }
      },
      fail: (err) => {
        console.error("获取评价次数失败", err);
      }
    });
  },

  fetchCollectionCount() {
    const { cid } = this.data;
    
    wx.request({
      url: `http://localhost:8080/courseStore/count`,
      method: "GET",
      data: {
        courseId: cid
      },
      success: (resp) => {
        if (resp.data.code === 200) {
          this.setData({
            collectionCount: resp.data.data || 0
          });
        }
      },
      fail: (err) => {
        console.error("获取收藏次数失败", err);
      }
    });
  },

  checkCollectionStatus() {
    console.log("课程收藏中");
    const { loginUserInfo, cid } = this.data;
    if (loginUserInfo) {
      const userId = loginUserInfo.id;
      wx.request({
        url: `http://localhost:8080/courseStore/check`,
        method: "GET",
        data: {
          userId,
          courseId: cid
        },
        success: (resp) => {
          console.log("课程收藏中",resp);
          const collectionList = resp.data.data;
          // const hasCollection = collectionList.some(item => item.del === 0);
          this.setData({
            // isCollected: hasCollection
            isCollected: collectionList
          });
        },
        fail: (err) => {
          console.error("查询课程收藏表失败", err);
        }
      });
    }
  },

  toggleCollection() {
    const { loginUserInfo, cid, isCollected } = this.data;
    if (!loginUserInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    const userId = loginUserInfo.id;
    if (isCollected) {
      // 取消收藏
      wx.request({
        url: `http://localhost:8080/courseStore/check`,
        method: "GET",
        data: {
          userId,
          courseId: cid
        },
        success: (resp) => {
          console.log("取消收藏:",resp);
          const collectionList = resp.data.data;
          // const collection = collectionList.find(item => item.del === 0);
          const collection = collectionList
          if (collection) {
            console.log("123");
            const id = collection;
            wx.request({
              url: `http://localhost:8080/courseStore/${id}`,
              method: "DELETE",
              success: (deleteResp) => {
                if (deleteResp.data.code === 200) {
                  this.setData({
                    isCollected: false
                  });
                  this.fetchCollectionCount();
                }
              },
              fail: (err) => {
                console.error("取消收藏失败", err);
              }
            });
          }
        },
        fail: (err) => {
          console.error("查询课程收藏表失败", err);
        }
      });
    } else {
      // 添加收藏
      wx.request({
        url: `http://localhost:8080/courseStore`,
        method: "POST",
        data: {
          courseId: cid,
          userId: userId
        },
        success: (resp) => {
          if (resp.data.code === 200) {
            this.setData({
              isCollected: true
            });
            this.fetchCollectionCount();
          }
        },
        fail: (err) => {
          console.error("添加收藏失败", err);
        }
      });
    }
  },

  checkPurchaseStatus() {
    const { loginUserInfo, cid } = this.data;
    if (loginUserInfo) {
      const userId = loginUserInfo.id;
      wx.request({
        url: `http://localhost:8080/courseOrder1`,
        method: "GET",
        data: {
          userId,
          courseId: cid
        },
        success: (resp) => {
          const orders = resp.data.data;
          const hasPurchased = orders.length > 0;
          this.setData({
            isPurchased: hasPurchased
          });
        },
        fail: (err) => {
          console.error("查询课程订单表失败", err);
        }
      });
    }
  },

  onLoad(options) {
    this.setData({
      cid: options.id,
      loginUserInfo: app.globalData.loginUserInfo
    });
    
    // 获取课程详情
    wx.request({
      url: `http://localhost:8080/course/${options.id}`,
      method: "GET",
      success: (courseResp) => {
        const courseData = courseResp.data.data;

        this.setData({
          course: courseData,
          courseid: courseData.id 
        }, () => {
          this.fetchAndFilterCourseVideos();
        });
      },
      fail: (err) => {
        console.error("获取课程详情失败", err);
      }
    });

    // 获取名师介绍
    wx.request({
      url: `http://localhost:8080/counselor/${options.id}`,
      method: "GET",
      success: (resp) => {
        this.setData({
          teacherintroduce: resp.data.data
        });
        console.log("咨询师",resp);
      },
      fail: (err) => {
        console.error("获取名师介绍失败", err);
      }
    });

    // 获取课程评价
    wx.request({
      url: `http://localhost:8080/courseEvaluate`,
      method: "GET",
      success: (resp) => {
        const filteredEvaluate = resp.data.data.filter(item => item.courseId == this.data.cid);
        this.setData({
          courseEvaluate: resp.data.data,
          courseEvaluate1: filteredEvaluate
        });
      },
      fail: (err) => {
        console.error("获取课程评价失败", err);
      }
    });

    // 查询课程订单表，判断用户是否已购买课程
    this.checkPurchaseStatus();
    console.log("查询课程收藏表前");

    // 查询课程收藏表，判断课程是否已收藏
    this.checkCollectionStatus();
    console.log("查询课程收藏表后");
    // 获取评价次数
    this.fetchEvaluationCount();

    // 获取收藏次数
    this.fetchCollectionCount();
  }
})